import java.io.*;
import java.util.Scanner;

public class AveragePriceCalculator {
    public static void main(String[] args) {
        File file = new File("prices.txt");

        Scanner sc = null;
        int count = 0;
        double sum = 0;

        try {
            sc = new Scanner(file);
            // 设置分隔符为非数字和非小数点的字符，这样可以读取由这些字符分隔的数字
            sc.useDelimiter("[^0-9.]+");
            while (sc.hasNextDouble()) {
                double price = sc.nextDouble();
                count++;
                sum += price;
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到: " + e.getMessage());
            return;
        } catch (Exception exp) {
            System.out.println("读取价格时发生错误: " + exp);
            return;
        } finally {
            if (sc != null) {
                sc.close();
            }
        }

        if (count > 0) {
            double average = sum / count;
            String formattedAverage = String.format("%.2f", average);

            // 将计算得到的平均价格追加到文件末尾
            try (FileWriter fw = new FileWriter(file, true)) {
                fw.write("\n平均价格:" + formattedAverage + "元");
            } catch (IOException e) {
                System.out.println("无法将平均价格写入文件: " + e.getMessage());
            }

            System.out.println("平均价格:" + formattedAverage + "元 已追加至文件。");
        } else {
            System.out.println("没有可用的价格来计算平均值。");
        }
    }
}